# -*- coding: utf-8 -*-
# filename: handle.py

import web
import json
import time
import random
from configcenter import configCenter
class prizeWinners(object):
    def GET(self):
        try:
            web.header("Access-Control-Allow-Origin", "*")
            web.header('content-type','text/json')
            cc = configCenter()
            config = cc.getConfig()
            host = config.get("global", "ip")
            port = config.get("global", "port")
            user = config.get("global", "user")
            pw = config.get("global", "password")
            database = config.get("global", "database")
            db = web.database(dbn='mysql', host=host, port=int(port), user=user, pw=pw, db=database)
            prizes = db.select('prize')
            fp = prizes[0]
            begintime = fp.begintime
            totalprize = fp.totalprize
            if begintime == "":
                datadict = {}
                datadict['data'] = ''
                datadict['result'] = 'false'
                datadict['msg'] = '游戏还未开始'
            else:
                before = int(time.mktime(time.strptime(begintime,'%Y-%m-%d %H:%M:%S')))
                now = int(time.time())
                pdata = []
                if((now - before)/60 > 10):
                    shareprize = int(totalprize*0.2)
                    nowtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                    bullets = db.select('bullet',where="uptime between '"+begintime + "' and '" + nowtime+"'")
                    mobilelist = []
                    winners = []
                    for bullet in bullets:
                        mobilelist.append(bullet.mobile)
                    mobilelist = list(set(mobilelist))
                    cost = 0
                    if len(mobilelist) < 10:
                        nums = len(mobilelist)
                        for i in range(0, nums):
                            curprize = self.calPrize(shareprize, nums -1 - i)
                            while curprize > shareprize / 3:
                                curprize = self.calPrize(shareprize, nums -1 - i)
                            shareprize = shareprize - curprize
                            db.insert('prizewinner',mobile=mobilelist[i],prize=curprize,uptime=nowtime)
                            winners.append(str(mobilelist[i])+"_"+str(curprize))
                            cost = cost + curprize
                        db.update('prize', totalprize=totalprize - cost)
                    else:
                        for i in range(0, 10):
                            curprize = self.calPrize(shareprize, 9 - i)
                            while curprize > shareprize / (10 - i):
                                curprize = self.calPrize(shareprize, 9 - i)
                            shareprize = shareprize - curprize
                            db.insert('prizewinner', mobile=mobilelist[i], prize=curprize, uptime=nowtime)
                            winners.append(str(mobilelist[i]) + "_" + str(curprize))
                            cost = cost + curprize
                        db.update('prize', totalprize=totalprize - cost)
                    datadict = {}
                    datadict['winners'] = pdata
                    datadict['prizeRemaining'] = 600 - (now - before)
                    datadict['result'] = True
                    return json.dumps(datadict)
                else:
                    winners = db.query('select * from prizewinner where uptime=(SELECT MAX(uptime) FROM prizewinner)')
                    for winner in winners:
                        pdata.append(winner.mobile+"_"+str(winner.prize))
                    datadict = {}
                    datadict['winners'] = pdata
                    datadict['prizeRemaining'] = 600 - (now - before)
                    datadict['result'] = 'true'
                    return json.dumps(datadict)
        except Exception as e:
            return e.args

    def calPrize(self,shareprize,left):
        return random.randint(1,shareprize - left)


